﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Log;

namespace PayManage
{
    public partial class frmSheetsManage : Form
    {
        private string currentSheet;
        private string currentFile; 
        private static readonly ILog logger = LogManager.GetLogger(typeof(frmSheetsManage));
        public frmSheetsManage()
        {
            InitializeComponent();
        }

        private void frmSheetsManage_Load(object sender, EventArgs e)
        {
            InitTreeView();
            this.menu_DataGridView.Items[3].Enabled = false;
        }

        private void InitTreeView()
        {

            for (int i = 0; i < DataService.ExcelSheetsConfigs.Sheets.Count; i++)
            {
                TreeNode sheetNode = new TreeNode(DataService.ExcelSheetsConfigs.Sheets[i].SheetName);
                sheetNode.Name = DataService.ExcelSheetsConfigs.Sheets[i].SheetName;
                //var cols = DataService.ExcelSheetsConfigs.Sheets[i].Columns;
                //for (int j = 0; j < cols.Count; j++)
                //{   
                    
                //}
                this.treeView1.Nodes.Add(sheetNode);
                
            }
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            string sheetName = e.Node.Name;
            if (currentSheet != sheetName)
            {
                //根据单击表头的名字查找表配置              
                this.dataGridView1.DataSource = GetColumnsFromCach(sheetName);
                    //this.dataGridView1.Refresh();
                 currentSheet = sheetName;
                 this.toolStripStatusLabel1.Text = "当前操作："+sheetName;
            }
            
        }

        private List<ColumnConfigEntity> GetColumnsFromCach(string sheetName)
        {
            List<ColumnConfigEntity> cols = (List<ColumnConfigEntity>)Caching.Cache["Columns" + sheetName];           
            if (cols == null)
            {
                var sheet = DataService.ExcelSheetsConfigs.Sheets.FirstOrDefault((s) => s.SheetName.Equals(sheetName));
                if (sheet != null)
                {
                    cols = new List<ColumnConfigEntity>();
                    foreach (var col in sheet.Columns)
                    {
                        cols.Add(DataService.Clone < ColumnConfigEntity>(col)); 
                    }
                    Caching.Cache["Columns" + sheetName] = cols;
                }
            }
            return cols;
        }

        private bool SaveCurrentSheetCols(string sheetName)
        {
            try
            {
                //List<ColumnConfigEntity> cols = (List<ColumnConfigEntity>)Caching.Cache["Columns" + sheetName];
                List<ColumnConfigEntity> cols = (List<ColumnConfigEntity>)this.dataGridView1.DataSource;
                if (cols != null)
                {
                    var index = DataService.ExcelSheetsConfigs.Sheets.FindIndex((s) => s.SheetName.Equals(sheetName));
                    if (index != -1)
                    {
                        DataService.ExcelSheetsConfigs.Sheets[index].Columns.Clear();
                        foreach (var col in cols)
                        {
                            DataService.ExcelSheetsConfigs.Sheets[index].Columns.Add(DataService.Clone<ColumnConfigEntity>(col));
                        }
                        DataService.SaveSheets();
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检查当前单元格的方法（避免查、改、增、删等操作报错）
        /// </summary>
        /// <returns></returns>
        private bool CheckCurrentCell()
        {
            if (this.dataGridView1.CurrentCell == null)
            {
                MessageBox.Show("请选择一行有效信息再执行操作！");
                return false;
            }
            else
            {
                return true;
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.treeView1.Nodes.Count; i++)
            {
                Caching.Cache["Columns" + this.treeView1.Nodes[i].Name] = null;
                this.DialogResult = DialogResult.OK;
            }
            this.Close();
        }

        private void SaveCurrentSheet()
        {
            int index = DataService.ExcelSheetsConfigs.Sheets.FindIndex((s) => s.SheetName.Equals(currentSheet));
            if (index != -1)
            {
                SheetConfigEntity sheet = new SheetConfigEntity();
                List<ColumnConfigEntity> cols = new List<ColumnConfigEntity>();
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    cols.Add(new ColumnConfigEntity
                    {
                        ColumnIndex = i,
                        Id = this.dataGridView1.Rows[i].Cells["Id"].Value.ToString(),
                        HeadText = this.dataGridView1.Rows[i].Cells["HeadText"].Value.ToString()
                    });
                }
                DataService.ExcelSheetsConfigs.Sheets[index].Columns = cols;
                DataService.SaveSheets();

            }
        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dataGridView1.RowHeadersWidth - 4,
               e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dataGridView1.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.CurrentCell == null)
            {
                MessageBox.Show("请选择一行有效信息再执行操作！");
                return;
            }
            if (this.dataGridView1.Rows.Count < 2)
            {

                MessageBox.Show("对不起，至少预留一条记录！", "操作提示");
                return;
            }
            //this.dataGridView1.Rows.RemoveAt(this.dataGridView1.CurrentCell.RowIndex);

        }

        private void tool_AddSheets_Click(object sender, EventArgs e)
        {
            //if (this.dataGridView1.CurrentCell == null)
            //{
            //    this.dataGridView1.Rows.Add();
            //}
            //else
            //{
            //    this.dataGridView1.Rows.Insert(this.dataGridView1.CurrentCell.RowIndex+1, 1);
            //}
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            //int index = columns.FindIndex((c) => c.ColumnIndex == e.RowIndex);
            //if (index != -1)
            //{ 
               
            //columns[index]
            //}
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(currentSheet))
                {
                    DataService.ShowErrorMsg("当前操作表为空");
                    return;
                }
                if (MessageBox.Show("确认保存？" + currentSheet, "此保存不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    bool result = SaveCurrentSheetCols(currentSheet);
                    if (result)
                    {
                     MessageBox.Show("保存文件成功");
                    }                  
                }
            }
            catch (Exception ex)
            {
                DataService.ShowErrorMsg(ex.Message);
            }        
        }

        private void tool_data_Insert_Click(object sender, EventArgs e)
        {
            try
            {
                List<ColumnConfigEntity> cols = (List<ColumnConfigEntity>)this.dataGridView1.DataSource;
                ColumnConfigEntity dr = new ColumnConfigEntity();

                var rows = this.dataGridView1.SelectedRows;
                int newRowIndex;
                if (rows == null)
                {
                    cols.Add(dr);
                }
                else
                {                    
                    //在选中位置新增一行，
                    cols.Insert(this.dataGridView1.Rows.IndexOf(rows[0]),dr);
                    
                }               
                this.dataGridView1.DataSource = cols;
                newRowIndex = cols.IndexOf(dr);
                this.dataGridView1.Rows[newRowIndex].Cells[1].ReadOnly = false;
                //this.dataGridView1.CurrentCell = this.dataGridView1.Rows[newRowIndex].Cells[0];

            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }

        }

        private void Alert(string message)
        {
            MessageBox.Show(message);
        }
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var rows = this.dataGridView1.SelectedRows;
            if (this.dataGridView1.SelectedRows == null)
            {
                Alert("对不起，选择要删除一行！");
                return;
            }
            string message = "您确实要删除选定记录吗？";
            string caption = "删除提醒";
            for (int i = 0; i < rows.Count; i++)
            {
                message += rows[i].Cells["HeadText"].Value + "\t";
            }
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result;
            result = MessageBox.Show(this, message, caption, buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
            if (result == DialogResult.Yes)
            {
                List<ColumnConfigEntity> cols = (List<ColumnConfigEntity>)this.dataGridView1.DataSource;
                for (int i = 0; i < rows.Count; i++)
                {
                    
                    int index = this.dataGridView1.Rows.IndexOf(rows[i]);
                    cols.RemoveAt(index);
                    //this.dataGridView1.Rows.RemoveAt(index);
                }
                //this.dataGridView1.Rows.Clear();
                this.dataGridView1.DataSource = cols;
                this.dataGridView1.Refresh();              
            }

        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var rows = this.dataGridView1.SelectedRows;
            if (this.dataGridView1.SelectedRows == null)
            {
                Alert("对不起，选择要复制一行！");
                return;
            }
            List<ColumnConfigEntity> cols = (List<ColumnConfigEntity>)this.dataGridView1.DataSource;
            Caching.Cache["CopyColumn"] = cols[this.dataGridView1.Rows.IndexOf(rows[0])];
            this.menu_DataGridView.Items[3].Enabled = true;
        }

        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var col = Caching.Cache["CopyColumn"];
                if (col != null)
                {
                    //当前单元格是否选择的判断
                    if (dataGridView1.CurrentCell == null)
                        return;
                    int insertRowIndex = dataGridView1.CurrentCell.RowIndex;
                    List<ColumnConfigEntity> cols = (List<ColumnConfigEntity>)this.dataGridView1.DataSource;
                    string id = cols[insertRowIndex].Id;
                    string headtext = cols[insertRowIndex].HeadText;
                    cols[insertRowIndex] = DataService.Clone<ColumnConfigEntity>((ColumnConfigEntity)col);
                    cols[insertRowIndex].Id = id;
                    cols[insertRowIndex].HeadText = headtext;
                    this.dataGridView1.DataSource = cols;
                    Alert("粘贴成功");
                }
                else
                {
                    Alert("没有复制数据");
                }
               
            }
            catch (Exception ex)
            {
                DataService.ShowErrorMsg(ex.Message);
            }
        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }  
    }
}
